package com.sxpi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxpi.common.result.Result;
import com.sxpi.model.dto.CouponsDto;
import com.sxpi.model.entity.Coupons;
import com.sxpi.model.page.PageResult;
import com.sxpi.model.vo.CouponsVo;
import com.sxpi.service.CouponsService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/coupons")
public class CouponsController {
    private static final Logger log = LoggerFactory.getLogger(CouponsController.class);
    @Resource
    private CouponsService couponsService;

    /**
     * @param pageNo
     * @param pageSize
     * @param id
     * @return
     */
    @GetMapping("/getAllCoupons")
    public Result<PageResult<Coupons>> getAllCoupons(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                     @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                     @RequestParam(required = false) Long id){
        return couponsService.getAllCoupons(pageNo, pageSize,id);
    }

    @GetMapping("/getValidCoupons")
    public Result<List<Coupons>> getValidCoupons() {
        return couponsService.getValidCoupons();
    }

    /**
     * 新增优惠券
     * @param coupons
     * @return
     */
    @PostMapping("/addCoupons/{count}")
    public Result<Boolean> addCoupons(@RequestBody Coupons coupons, @PathVariable Integer count) {
        return couponsService.addCoupons(coupons,count);
    }

    //查询用户所对应的优惠券
    @GetMapping("/getAllCoupons/{userId}")
    public Result<List<CouponsVo>> getAllCouponsById(@PathVariable Long userId,
                                                     @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                     @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                     @RequestParam(required = false, defaultValue = "1") Integer status) {

        return couponsService.getAllCouponsByUser(userId , pageNo, pageSize, status);
    }


    //兑换优惠券
    @PostMapping("/exchangeCoupons")
    public Result<Boolean> exchangeCoupons(@RequestBody String data ){
        JSONObject jsonObject = JSONArray.parseObject(data);
        String code = jsonObject.getString("code");
        Long userId = Long.valueOf(jsonObject.getString("userId"));

        return couponsService.exchangeCoupons(code,userId);
    }

} 